package com.yc.upload.web;

import com.yc.upload.UploadProperties;
import com.yc.upload.bean.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
public class UploadAction {

    @Resource
    private UploadProperties uploadProperties;

    @PostMapping("upload")
    public Result upload(@RequestParam("file") MultipartFile file) throws IOException {
        String diskpath = uploadProperties.getDiskpath();
        // 对文件名重新命名 => 随机 a.jpg ==> adfjlkajklafd.jpg
        String filename = file.getOriginalFilename();
        // 提取文件名后缀
        String suffix = filename.replaceAll(".+\\.(\\w+)", "$1");
        String newFilename = UUID.randomUUID().toString();
        // 去掉 - 号
        newFilename = newFilename.replaceAll("-", "");
        newFilename += "." + suffix;
        // 保存本地文件路径
        File f = new File(diskpath, newFilename);
        file.transferTo(f);
        String webpath = uploadProperties.getWebpath();
        webpath += newFilename;
        return new Result(1,"文件上传成功",webpath);
    }

    @PostMapping("uploads")
    public Result uploads(@RequestParam("file") MultipartFile[] files) throws IOException {
        List<Map<String,String>> list = new ArrayList<>();
        for (MultipartFile file : files) {
            Result res = upload(file);
            if (res.getCode() == 1){
                Map<String,String> map = new HashMap<>();
                map.put("srcFile", file.getOriginalFilename());
                map.put("destFile", (String) res.getData());
                list.add(map);
            }
        }
        return new Result(1,"文件上传成功",list);
    }
}
